package com.xique.door.project.miniprogram.biz.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.xique.common.core.domain.R;
import com.xique.common.core.utils.OrikaUtil;
import com.xique.common.core.utils.SecurityUtils;
import com.xique.common.core.utils.StringUtils;
import com.xique.common.core.web.domain.AjaxResult;
import com.xique.common.security.service.AppTokenServiceV2;
import com.xique.door.api.model.LoginAppUser;
import com.xique.door.bean.domain.AccessDeviceV1;
import com.xique.door.bean.domain.User;
import com.xique.door.bean.domain.UserV1;
import com.xique.door.bean.search.device.DeviceListSearch;
import com.xique.door.project.miniprogram.bean.request.MiniChooseCommunityRequest;
import com.xique.door.project.miniprogram.bean.vo.MiniCommunityListVO;
import com.xique.door.project.miniprogram.biz.service.IMiniHomeBizService;
import com.xique.door.service.IAccessDeviceService;
import com.xique.door.service.IUserService;
import com.xique.system.api.RemoteSystemProjectService;
import com.xique.system.api.dto.SystemProjectDTO;
import com.xique.system.api.request.RemoteSystemProjectAllListRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author shd
 * @create 2022/4/12 16:56
 */
@Service
public class MiniHomeBizServiceImpl implements IMiniHomeBizService {

    @Autowired
    private RemoteSystemProjectService projectService;

    @Autowired
    private AppTokenServiceV2 appTokenServiceV2;

    @Autowired
    private IUserService userService;

    @Autowired
    private IAccessDeviceService accessDeviceService;

    @Override
    public AjaxResult getBaseInfo() {

        Map<String, Object> map = new HashMap<>();
        map.put("baseUserId", SecurityUtils.getBaseUserId());
        map.put("userId", SecurityUtils.getUserId());
        map.put("userName", SecurityUtils.getUsername());
        map.put("parkId", SecurityUtils.getParkId());
        map.put("isInvitationCode", false);
        if (StringUtils.isNotNull(SecurityUtils.getParkId())) {
            R<SystemProjectDTO> result = projectService.getProjectInfo(SecurityUtils.getParkId());
            if (R.SUCCESS == result.getCode()) {
                SystemProjectDTO dto = result.getData();
                map.put("parkName", dto.getName());
            }
            DeviceListSearch search = new DeviceListSearch();
            search.setParkId(SecurityUtils.getParkId());
            List<AccessDeviceV1> devices = accessDeviceService.selectFreeviewDeviceList(search);
            if (CollectionUtil.isNotEmpty(devices)) {
                map.put("isInvitationCode", true);
            }
            if (StringUtils.isNotNull(SecurityUtils.getUserId())) {
                UserV1 userV1Search = new UserV1();
                userV1Search.setParkId(SecurityUtils.getParkId());
                userV1Search.setBaseUserId(SecurityUtils.getBaseUserId());
                UserV1 userV1 = userService.selectUserV1(userV1Search);
                if (StringUtils.isNotNull(userV1)) {
                    map.put("parkUserName", userV1.getUserName());
                    map.put("phone", userV1.getPhone());
                    LoginAppUser loginAppUser = appTokenServiceV2.getLoginUser();
                    loginAppUser.setUserId(userV1.getId());
                    appTokenServiceV2.refreshToken(loginAppUser);
                }
            }
        } else {
            List<User> userList = userService.selectUserByBaseUserId(SecurityUtils.getBaseUserId());
            if (CollectionUtil.isNotEmpty(userList) && userList.size() == 1) {
                User user = userList.get(0);
                LoginAppUser loginAppUser = appTokenServiceV2.getLoginUser();
                loginAppUser.setUserId(user.getId());
                loginAppUser.setParkId(user.getParkId());
                appTokenServiceV2.refreshToken(loginAppUser);

                map.put("userId", user.getId());
                map.put("parkId", user.getParkId());
                map.put("parkUserName", user.getUserName());
                map.put("phone", user.getPhone());
                R<SystemProjectDTO> result = projectService.getProjectInfo(user.getParkId());
                if (R.SUCCESS == result.getCode()) {
                    SystemProjectDTO dto = result.getData();
                    map.put("parkName", dto.getName());
                }
                DeviceListSearch search = new DeviceListSearch();
                search.setParkId(SecurityUtils.getParkId());
                List<AccessDeviceV1> devices = accessDeviceService.selectFreeviewDeviceList(search);
                if (CollectionUtil.isNotEmpty(devices)) {
                    map.put("isInvitationCode", true);
                }
            }
        }

        return AjaxResult.success(map);
    }

    @Override
    public AjaxResult getCommunityList(String areaCode) {

        RemoteSystemProjectAllListRequest request = new RemoteSystemProjectAllListRequest();
        request.setIsDoor("Y");
        request.setAreaCode(areaCode);

        R<List<SystemProjectDTO>> result = projectService.getProjectList(request);
        if (R.FAIL == result.getCode()) {
            return AjaxResult.error(result.getMsg());
        }

        List<SystemProjectDTO> list = result.getData();

        List<MiniCommunityListVO> vos = OrikaUtil.converts(list, MiniCommunityListVO.class);

        Map<String, Object> map = new HashMap<>(1);
        map.put("list", vos);

        return AjaxResult.success(map);
    }

    @Override
    public AjaxResult chooseCommunity(MiniChooseCommunityRequest request) {

        R<SystemProjectDTO> result = projectService.getProjectInfo(request.getId());
        if (R.FAIL == result.getCode()) {
            return AjaxResult.error(result.getMsg());
        }

        SystemProjectDTO project = result.getData();

        UserV1 search = new UserV1();
        search.setBaseUserId(SecurityUtils.getBaseUserId());
        search.setParkId(project.getId());
        UserV1 user = userService.selectUserV1(search);

        LoginAppUser loginAppUser = appTokenServiceV2.getLoginUser();
        loginAppUser.setParkId(project.getId());
        if (StringUtils.isNotNull(user)) {
            loginAppUser.setUserId(user.getId());
        } else {
            loginAppUser.setUserId(null);
        }
        appTokenServiceV2.refreshToken(loginAppUser);

        return AjaxResult.success();
    }
}
